import requests
import base64
import os
import cv2
import numpy as np
from openai import OpenAI

API_KEY = os.environ.get("GITEEAI_API_KEY")
X_PACKAGE = "1910"

def convert_image_style(inputs, prompt, output_path):
    """
    转换图片风格的简化函数
    
    Args:
        inputs (str): 需要转换的原始图片路径
        prompt (str): 转换提示词
        output_path (str): 输出图片路径
    
    Returns:
        bool: 转换是否成功
    """
    # API配置
    API_URL = "https://ai.gitee.com/api/serverless/Kolors/image-to-image"
    headers = {
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
        "X-Package": X_PACKAGE
    }
    
    try:
        # 读取参考图片
        refer_path = os.path.join("assets", "refer_image.png")
        with open(refer_path, "rb") as image_file:
            refer_image = base64.b64encode(image_file.read()).decode('utf-8')
        
        # 构建请求参数
        payload = {
            "parameters": {
                "prompt": prompt,
                "width": 1024,
                "height": 1024,
                "steps": 25,
                "guidance_scale": 6,
                "strength": 0.6,
                "scale": 0.5
            },
            "image": refer_image,
            "inputs": inputs
        }
        
        # 发送请求
        response = requests.post(API_URL, headers=headers, json=payload)
        
        # 保存结果
        with open(output_path, "wb") as file:
            file.write(response.content)
        return True
        
    except Exception as e:
        print(f"转换失败: {str(e)}")
        return False
    
def get_image_description(image: str) -> str:
    """
    使用OpenAI API获取图片描述
    
    参数:
        image: 图片base64
    
    返回:
        图片描述文本
    """
    client = OpenAI(
        base_url="https://ai.gitee.com/v1",
        api_key=API_KEY,
        default_headers={"X-Package": X_PACKAGE},
    )
    
    response = client.chat.completions.create(
        model="Qwen2-VL-72B",
        stream=False,
        max_tokens=512,
        temperature=0.7,
        top_p=1,
        extra_body={
            "top_k": -1,
        },
        frequency_penalty=0,
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "请告诉我图片主体，使用简洁语言回复，不包括“图片主体是”，返回格式为数词+量词+主体，比如“一个装有茶水的茶杯”，“一只奔跑的小狗”"
                    },
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/png;base64,{image}"
                        }
                    }
                ]
            }
        ],
    )
    
    return response

def generate_sketch(image_path, output_path=None):
    """
    生成图片的线稿效果
    
    Args:
        image_path (str): 输入图片路径
        output_path (str, optional): 输出图片路径，默认为None
        
    Returns:
        numpy.ndarray: 处理后的线稿图片数组
    """
    # 读取图片
    img = cv2.imread(image_path)
    
    # 转换为灰度图
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # 反转灰度图
    inverted = cv2.bitwise_not(gray)
    
    # 高斯模糊
    blurred = cv2.GaussianBlur(inverted, (21, 21), sigmaX=0, sigmaY=0)
    
    # 再次反转
    inverted_blurred = cv2.bitwise_not(blurred)
    
    # 生成素描效果
    sketch = cv2.divide(gray, inverted_blurred, scale=256.0)
    
    # 如果指定了输出路径，保存图片
    if output_path:
        cv2.imwrite(output_path, sketch)
    
    return sketch 